package com.dev.module_ui_composable.view.ad

import android.app.Activity
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.heightIn
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalLifecycleOwner
import androidx.compose.ui.unit.dp
import androidx.compose.ui.viewinterop.AndroidViewBinding
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleEventObserver
import com.dev.module_ui_composable.databinding.BannerAdLayoutBinding
import com.fwlst.lib_base.utils.AdUtils


/**
 * 穿山甲 Banner广告
 */
@Composable
fun BannerAdView(modifier: Modifier = Modifier) {
    val context = LocalContext.current
    val lifecycleOwner = LocalLifecycleOwner.current

    AndroidViewBinding(
        factory = { inflater, parent, attachToParent ->
            BannerAdLayoutBinding.inflate(inflater, parent, attachToParent)
        },
        modifier = modifier
            .fillMaxWidth()
            .heightIn(min = 0.dp),
        update = {
            // 加载广告
            AdUtils.loadBannerAd(context as Activity, bannerContainer)
        }
    )

    // 使用 DisposableEffect 监听 LifecycleOwner 的生命周期
    DisposableEffect(lifecycleOwner) {
        val lifecycleObserver = LifecycleEventObserver { _, event ->
            when (event) {
                Lifecycle.Event.ON_DESTROY -> {
                    // 销毁广告
                    AdUtils.destroyBannerAd()
                }
                else -> {}
            }
        }

        // 将观察者添加到 LifecycleOwner
        lifecycleOwner.lifecycle.addObserver(lifecycleObserver)

        // 在 Composable 销毁时，从 LifecycleOwner 移除观察者，并执行清理操作
        onDispose {
            lifecycleOwner.lifecycle.removeObserver(lifecycleObserver)
        }
    }
}
